<?php

namespace app\admin\controller\workteam\analysis;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;


/**
 * 月度报表
 */
class Statement extends Backend
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList=[];
    public function _initialize()
    {
        parent::_initialize();

        $this->getGroupData();
        $this->assignconfig("admin", ['id' => $this->auth->id]);
        $this->model = new  \app\admin\model\workteam\Statement();

    }


    protected function getGroupData(){

        $department = get_addon_info('department');
        if ($department && $department['state'] == 1) {
            $groupdata = \app\admin\model\department\Admin::getAllDepartmentsTreeArray($this->auth->id, $this->auth->isSuperAdmin());
        } else {
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
            $this->groupList=$groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
            Tree::instance()->init($groupList);
            $groupdata = [];
            if ($this->auth->isSuperAdmin()) {
                $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
                foreach ($result as $k => $v) {
                    $groupdata[$v['id']] = $v['name'];
                }
            } else {
                $result = [];
                $groups = $this->auth->getGroups();
                foreach ($groups as $m => $n) {
                    $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                    $temp = [];
                    foreach ($childlist as $k => $v) {
                        $temp[$v['id']] = $v['name'];
                    }
                    $result[__($n['name'])] = $temp;
                }
                $groupdata = $result;
            }
        }




        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 数据查看
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index(){



        $scene = model('\app\admin\model\workteam\Scene');
        $scene_list = $scene->where('types', 'statement')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        if ($this->request->isAjax()) {
            $filter_w = $this->getFilterWhere($scene_list);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return parent::selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                }])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->assignconfig("scene_list", $scene_list);
        $this->view->assign("scene_list", $scene_list);

        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        set_time_limit(0);
        $adminModel=new \app\admin\model\Admin();
        $statement=new \app\admin\model\workteam\Statement();
        if ($this->request->isPost()){

            $params = $this->request->post("row/a");
            if (!$params['year'])
                $params['year']=date('Y');
            if (!$params['month'])
                $params['month']=date('m');

            $statistics_cache_name=md5('statistics_cache_name'.$params['year'].$params['month']);

            if ($params['admin_id']){
                $lists=$adminModel->where('id','in',$params['admin_id'])->select();
            }else{
                $last_admin_id=intval(session($statistics_cache_name));
                $lists=$adminModel->where('id','>',$last_admin_id)->order('id asc')->limit(1)->select();
            }
            foreach ($lists as $row){
                \app\admin\model\workteam\Statement::statistics($params['year'],$params['month'],$row->id);
                if (isset($last_admin_id)) session($statistics_cache_name,$row->id);

            }
            if (!$lists)session($statistics_cache_name,0);
            $this->success("",'',$lists?1:0);
        }



        $this->assignconfig("acount",$adminModel->count());
        return $this->view->fetch();
    }

    /**
     * 确认报表
     * @param null $ids
     */
    public function confirm($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->status==1)
            $this->error(__('已经确认过，无需再确认'));


       $st_time= \app\admin\model\workteam\Statement::mFristAndLast($row['year'],$row['month']);
       if ($st_time['end_time']>time()){
           $this->error(__('还未到确定时间'));
       }

        if ($st_time['end_time']>$row['update_time']){
            $this->error(__('业绩尚未更新，不能确定'));
        }
        $auth=new \addons\workteam\library\Auth();
        $childrenAdminIds =$auth->childrenAdminIds($this->auth,true);
        //判断是否有权限确定
        if (!in_array($row['admin_id'], $childrenAdminIds)){
            $this->error(__('你没有权限'));
        }
        $row->status=1;
        $row->save();
        return $this->success(__("成功"));

    }
    /**
     * 编辑
     * @internal
     */
    public function edit($ids = null)
    {
        $this->error();
    }

    /**
     * 删除
     * @internal
     */
    public function del($ids = "")
    {
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }
    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter_w['admin_id'] = $this->auth->id;
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 9;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            $auth = new \addons\workteam\library\Auth();
            switch ($filter['scene_id']) {
                case 9:
                    //全部
                    $this->childrenAdminIds = $auth->childrenAdminIds($this->auth,true);
                    if ($this->childrenAdminIds)
                        $filter_w['admin_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 10:
                    //我的
                    $filter_w['admin_id'] = $this->auth->id;
                    break;
                case 11:
                    //下属
                    $this->childrenAdminIds = $auth->childrenAdminIds($this->auth,false);
                    if ($this->childrenAdminIds){
                        $filter_w['admin_id'] = ['in', $this->childrenAdminIds];
                    }else{
                        $filter_w['admin_id'] ='-1';
                    }

                    break;
                default://其它的还做TODO
                    $filter_w['admin_id'] = $this->auth->id;
            }
            if (isset($filter['expire_type'])) {
                $this->expire_type = $filter['expire_type'];
                unset($filter['expire_type']);
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }

}
